$(() => {
    $('.o-lt-video').each((i, video_block) => {
        // Парсим таймкоды из <style>
        const time_codes = parseTimestamps($(video_block).find('> style:first-child').text());
        
        if (time_codes.length > 0) {
            // Добавляем блок для таймкодов
            $(video_block).find('.vhi-root').append('<div class="block_time-codes closed"><span class="open_timecodes">Тайм-коды</span><span class="overfill"><div class="inner_Codes"></div></span></div>');
            
            // Получаем videoHash и iframe
            const videoHash = $(video_block).find('.vhi-root').attr('data-video-hash');
            const iframe = $(video_block).find('.vhi-root iframe')[0]; // Находим iframe внутри .vhi-root
            const targetOrigin = iframe ? new URL(iframe.src).origin : '*'; // Динамический домен
            const getLastSeenTimeUrl = $(video_block).find('.vhi-root').attr('data-get-last-seen-time');
            const timecodes = [];
            
            // Создаем ссылки для таймкодов
            time_codes.forEach(code => {
                const timeText = code.time;
                const timeInSeconds = code.seconds;
                timecodes.push(timeInSeconds);
                const link = $(`<a href="#goto-${videoHash}-${timeInSeconds}">${code.description} <strong>${code.time}</strong><span class="timecode_progress"><span class="timecode_progressLine"></span></span></a>`);
                $(video_block).find('.inner_Codes').append(link);
            });

            // Toggle-функционал для блока таймкодов
            $(video_block).find('.open_timecodes').on('click', () => {
                const tc_block = $(video_block).find('.block_time-codes');
                if (tc_block.hasClass('closed')) {
                    tc_block.addClass('opened').removeClass('closed');
                } else {
                    tc_block.addClass('closed').removeClass('opened');
                }
            });

            // Отслеживание времени и подсветка таймкодов
            if (iframe) {
                let lastCurrentTime = 0; // Последнее известное время
                let isPlaying = false; // Состояние воспроизведения
                let lastUpdateTime = Date.now(); // Время последнего обновления

                // Функция проверки временных меток
                function checkTimecodes(currentTime, videoHash) {
                    let activeTime = null;
                    let nextTime = null;

                    // Находим ближайший таймкод, меньший или равный текущему времени
                    for (let i = 0; i < timecodes.length; i++) {
                        if (currentTime >= timecodes[i]) {
                            activeTime = timecodes[i]; // Сохраняем последний подходящий таймкод
                            nextTime = i + 1 < timecodes.length ? timecodes[i + 1] : null; // Следующий таймкод
                        } else {
                            break; // Выходим, если текущий таймкод больше времени
                        }
                    }

                    // Подсвечиваем ссылку и обновляем прогресс
                    $(video_block).find('.inner_Codes a').removeClass('active').find('.timecode_progressLine').css('width', '0%'); // Сбрасываем active и прогресс
                    if (activeTime !== null) {
                        const link = $(video_block).find(`a[href="#goto-${videoHash}-${activeTime}"]`);
                        if (link.length) {
                            link.addClass('active');
                            // Рассчитываем прогресс
                            if (nextTime !== null) {
                                const progress = ((currentTime - activeTime) / (nextTime - activeTime)) * 100;
                                const progressPercent = Math.min(Math.max(progress, 0), 100).toFixed(2); // Ограничиваем 0-100%
                                link.find('.timecode_progressLine').css('width', `${progressPercent}%`);
                                console.log(`[Video ${videoHash}] Прогресс таймкода ${activeTime}: ${progressPercent}%`);
                            } else {
                                link.find('.timecode_progressLine').css('width', '0%'); // Последний таймкод — прогресс 0%
                                console.log(`[Video ${videoHash}] Активирован последний таймкод ${activeTime}, прогресс: 0%`);
                            }
                        } else {
                            console.error(`[Video ${videoHash}] Ссылка для таймкода ${activeTime} не найдена`);
                        }
                    } else {
                        console.log(`[Video ${videoHash}] Нет подходящего таймкода для ${currentTime.toFixed(2)} секунд`);
                    }
                }

                // Обработчик сообщений от iframe
                window.addEventListener('message', (event) => {
                    if (event.origin === targetOrigin && event.source === iframe.contentWindow && event.data.action === 'vh-video-event' && event.data.detail && typeof event.data.detail.currentTime === 'number') {
                        const currentTime = event.data.detail.currentTime;
                        const eventType = event.data.detail.eventType;

                        // Обновляем состояние
                        lastCurrentTime = currentTime;
                        lastUpdateTime = Date.now();
                        isPlaying = eventType === 'playing' || eventType === 'play' || eventType === 'volume-play';

                        // Проверяем временные метки
                        checkTimecodes(currentTime, videoHash);
                    }
                });

                // Периодическая проверка каждые 4 секунд
                setInterval(() => {
                    if (isPlaying) {
                        const elapsedSeconds = (Date.now() - lastUpdateTime) / 1000;
                        const estimatedTime = lastCurrentTime + elapsedSeconds;
                        checkTimecodes(estimatedTime, videoHash);
                    }
                    
                    iframe.contentWindow.postMessage(
                        {
                            action: 'vh-video-action',
                            detail: {
                                eventType: 'getCurrentTime'
                            }
                        },
                        targetOrigin
                    );
                }, 4000);

                // Запрашиваем начальное время с сервера
                if (getLastSeenTimeUrl) {
                    fetch(getLastSeenTimeUrl)
                        .then(response => response.json())
                        .then(data => {
                            if (data && typeof data.currentTime === 'number') {
                                lastCurrentTime = data.currentTime;
                                lastUpdateTime = Date.now();
                                checkTimecodes(data.currentTime, videoHash);
                            } else {
                                console.error(`[Video ${videoHash}] Не удалось получить начальное время:`, data);
                            }
                        })
                        .catch(error => console.error(`[Video ${videoHash}] Ошибка при запросе начального времени:`, error));
                } else {
                    console.error(`[Video ${videoHash}] URL для начального времени не найден`);
                }

                // Повторные попытки запроса getCurrentTime для iframe
                let attemptCount = 0;
                const maxAttempts = 5; // Пытаться 5 раз с интервалом 2 секунды
                const initialTimeInterval = setInterval(() => {
                    if (attemptCount >= maxAttempts) {
                        clearInterval(initialTimeInterval);
                        return;
                    }

                    if (iframe.contentWindow) {
                        iframe.contentWindow.postMessage(
                            {
                                action: 'vh-video-action',
                                detail: {
                                    eventType: 'getCurrentTime'
                                }
                            },
                            targetOrigin
                        );
                    } else {
                        console.error(`[Video ${videoHash}] Iframe не готов для попытки ${attemptCount + 1}`);
                    }
                    attemptCount++;
                }, 2000);

                // Проверяем начальное время сразу, если оно уже есть
                if (lastCurrentTime > 0) {
                    checkTimecodes(lastCurrentTime, videoHash);
                }
            } else {
                console.error(`[Video ${videoHash}] Iframe не найден`);
            }
        }
    });
});

function parseTimestamps(text) {
    // Удаляем идентификатор из начала текста
    const cleanText = text.replace(/^#ltBlock\d+\s*/, '');

    // Разделяем текст на строки и фильтруем непустые
    const lines = cleanText.split('\n').filter(line => line.trim());

    // Преобразуем строки в массив объектов
    return lines.map(line => {
        // Регулярное выражение для форматов H:MM:SS, HH:MM:SS или MM:SS
        const match = line.match(/^(?:(\d{1,2}):)?(\d{2}):(\d{2})\s*-\s*(.*)$/);
        if (match) {
            const hours = match[1] ? parseInt(match[1], 10) : 0; // Часы (если есть)
            const minutes = parseInt(match[2], 10);
            const seconds = parseInt(match[3], 10);
            const timeInSeconds = hours * 3600 + minutes * 60 + seconds;
            const timeText = match[1] ? `${hours}:${match[2]}:${match[3]}` : `${match[2]}:${match[3]}`; // Сохраняем исходный формат
            console.log(`[ParseTimestamps] Спарсен таймкод: ${timeText} -> ${timeInSeconds} секунд`);
            return {
                time: timeText, // Время в исходном формате (H:MM:SS или MM:SS)
                seconds: timeInSeconds, // Время в секундах
                description: match[4].trim() // Описание
            };
        }
        return null;
    }).filter(item => item !== null);
}